package cn.yinzhiping.redislearn.controller;

import cn.yinzhiping.redislearn.domain.User;
import cn.yinzhiping.redislearn.service.PublisherService;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.*;

/**
 * @author yinzhiping
 */
@RestController
public class TestRedisController {
    @Autowired
    private PublisherService publisherService;

    final StringRedisTemplate stringRedisTemplate;

    final RestTemplate restTemplate;

    public TestRedisController(StringRedisTemplate stringRedisTemplate, RestTemplate restTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.restTemplate = restTemplate;
    }

    @RequestMapping("/redis")
    public String getData() throws InterruptedException {
        Boolean flagger = stringRedisTemplate.hasKey("resData");
        String resData;
        if(flagger){
            resData = stringRedisTemplate.opsForValue().get("resData");
            return resData;
        }
        Thread.sleep(3000);
        String url = "http://218.75.72.53:9091/sjzhpt/yjxx?zcode=58457";
        resData = restTemplate.getForObject(url,String.class);
        assert resData != null;
        stringRedisTemplate.opsForValue().set("resData",resData);
        stringRedisTemplate.expire("resData",10, TimeUnit.SECONDS);
        return resData;
    }


    /**
     * 多线程
     */
    @RequestMapping("/select")
    public String testMany(){

        //定义一个拥有20个并发的线程池对象
        //ExecutorService service = Executors.newFixedThreadPool(20);
        ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
        //定义一个最终执行任务的线程对象
//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//                System.out.println("zdy现在很牛逼！");
//            }
//        };
        //Runnable runnable = new Runnable(()-> System.out.println("zdy现在很牛逼！"));a
        Runnable runnable  = new Thread( () -> System.out.println("zdy现在很牛逼！!!") );
        for (int i = 0; i < 100; i++) {
            //提交线程，并并发执行
            service.submit(runnable);
        }
        service.shutdown();
        return "abc";
    }

    /**
     * 发送请求之后立马返回结果
     * service其实在这里是一个生产者的角色，
     * 接收到前台传来的参数（请求），马上将参数写入到消息队列，然后立马返回结果
     * 消费者订阅了生产者，可以慢慢将参数内容持久化  或者其他操作
     * 场景（例如：大量用户同时注册一个网站，手机发送验证码功能，可以将手机号写入消息队列，立马返回这测成功，然后在消费者发送消息）
     * @param name
     * @return
     */
    //@RequestMapping("{name}")
    public String sendMessage(@PathVariable("name") String name) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        //return publisherService.sendMessage(name);
        ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
        Runnable runnable  = new Thread( () -> publisherService.sendMessage(name) );
        for (int i = 0; i < 100; i++) {
            //提交线程，并并发执行
            service.submit(runnable);
        }
        return "注册成功";
    }
}
